package com.jingdianjichi.wx.handler;

import com.jingdianjichi.wx.enums.MsgTypeEnum;
import com.jingdianjichi.wx.utils.redis.RedisUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
public class ReceiveTextMsgHandler implements MsgTypeHandler{

    public static final String KEY_WORD = "验证码";

    public static final String LOGIN_PREFIX = "login";

    @Resource
    private RedisUtil redisUtil;
    @Override
    public MsgTypeEnum getByMsgType() {
        return MsgTypeEnum.TEXT;
    }

    @Override
    public String handle(Map<String, String> map) {
        String content = map.get("Content");
        if(!KEY_WORD.equals( content)){
            return "";
        }
        Random random = new Random();
        int code = random.nextInt(10000);
        String codeStr = "您的验证码是"+code +",五分钟内有效";
        String fromUserName = map.get("FromUserName");
        String toUserName = map.get("ToUserName");

        String codeKey = redisUtil.buildKey(LOGIN_PREFIX,String.valueOf(code));
        redisUtil.setNx(codeKey,fromUserName,5L, TimeUnit.MINUTES);
        String msg = "<xml>\n" +
                "  <ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
                "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA["+codeStr+"]]></Content>\n" +
                "</xml>";

        return msg;
    }
}
